<template>
  <!-- 历年累计时间完成情况 -->
  <div>
    <!-- 上方图表 -->
    <div class="top">
      <v-chart
        ref="mycharts"
        style="height: 100%;width: 100%;"
        :options="optionsData"
        autoresize
      >
      </v-chart>
      <div class="block">
        <div style="width: 60%;display: flex;align-items: center;">
          <span style="width: 60px">单位：</span>
          <el-cascader
            v-model="dwxh"
            placeholder="请选择"
            :options="unitArr"
            @change="getUnitData"
            ref="unitCascader"
            :props="{ checkStrictly: true,emitPath: false }"
            clearable
            size="mini"
            :show-all-levels="false"
            popper-class="cas-class"
          ></el-cascader>
        </div>
        <div style="width: 40%;margin-left: 20px;">
          <el-slider
            v-model="value"
            show-stops
            :max="2"
            @change="getSliderChange"
            :format-tooltip="getFormatTooltip"
          >
          </el-slider>
        </div>
      </div>
    </div>
    <!-- 底部表格 -->
    <div class="mainTable_one">
      <sy-table
        :tab-header-data="tabHeaderData"
        :table-data="tableData"
        :loading="loading"
        :tab-index="false"
        :table-headerstyle="tableHeaderstyle"
        :tab-height="maxHeight"
        :tab-title="tabTitle"
        :col-span="colSpan"
      >
      </sy-table>
    </div>
  </div>
</template>
<script>
import { fillYears, getArrayObjectDeduplication, getTimeOfThisYear, getColumnFun, minutesToHours } from '../../../overallSituation.js'
import Api from '../../../api/https_lssj.js'
import Apis from '../../../api/http_historicalData'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  data () {
    return {
      optionsData: {},
      // 表头数据
      tabHeaderData: [
        { prop: 'DWJC', label: '单位', width: '160' },
        { prop: 'ND', label: '年份', width: '80' },
        { prop: 'zbnum', label: '时间指标', width: '100' },
        {
          label: '1月',
          children: [
            { prop: '1_Time', label: '飞行时间' },
            { prop: '1_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '2月',
          children: [
            { prop: '2_Time', label: '飞行时间' },
            { prop: '2_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '3月',
          children: [
            { prop: '3_Time', label: '飞行时间' },
            { prop: '3_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '4月',
          children: [
            { prop: '4_Time', label: '飞行时间' },
            { prop: '4_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '5月',
          children: [
            { prop: '5_Time', label: '飞行时间' },
            { prop: '5_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '6月',
          children: [
            { prop: '6_Time', label: '飞行时间' },
            { prop: '6_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '7月',
          children: [
            { prop: '7_Time', label: '飞行时间' },
            { prop: '7_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '8月',
          children: [
            { prop: '8_Time', label: '飞行时间' },
            { prop: '8_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '9月',
          children: [
            { prop: '9_Time', label: '飞行时间' },
            { prop: '9_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '10月',
          children: [
            { prop: '10_Time', label: '飞行时间' },
            { prop: '10_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '11月',
          children: [
            { prop: '11_Time', label: '飞行时间' },
            { prop: '11_WCL', label: '累计完成率' }
          ]
        },
        {
          label: '12月',
          children: [
            { prop: '12_Time', label: '飞行时间' },
            { prop: '12_WCL', label: '累计完成率' }
          ]
        }
      ],
      // 显示数据
      tableData: [],
      maxHeight: '50vh',
      // 表格加载动画
      loading: false,
      tabTitle: {
        showDiv: false
      },
      tableHeaderstyle: {
        background: '#8EBDFE',
        color: '#FFFFFF',
        fontSize: '14px'
      },
      colSpan: {
        rowSpanState: true,
        columnArray: [0], // 合并列数
        rowArray: [] // 每列合并数量
      },
      value: 1,
      dwxh: '',
      unitArr: []
    }
  },
  computed: {
    ...mapGetters('user', {
      currentUser: 'currentUser'
    })
  },
  created () {
  },
  props: {
    form: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  mounted () {
    const dwxh = this.currentUser.sysUnit.unitId
    this.dwxh = dwxh
    this.getUntilList(this.dwxh)
    this.getTableData()
    // --------图表----------
    const zt = (this.value + 1).toString()
    const param = {
      dwxh: this.dwxh,
      kssj: moment(this.form.kssj).format('YYYY'),
      jssj: moment(this.form.jssj).format('YYYY')
    }
    this.getCumCompleteData(param, zt)
  },
  methods: {
    // 日接口
    getJZBLSJWCQK (obj, zt) {
      Apis.getSJZBWCQKTable(JSON.stringify(obj)).then((result) => {
        const data = result.rows
        if (data.length !== 0) {
          console.log('data', data)
          this.echartDataProcessing(data, obj.kssj, obj.jssj, zt)
        } else {
          this.echartDataProcessing([], obj.kssj, obj.jssj, zt)
        }
      }).catch((err) => {
        console.log('err', err)
      })
    },
    // 月份接口
    getCumCompleteData (param, zt) {
      Apis.getHistoriesFlightTimeForLine(JSON.stringify(param)).then((result) => {
        const data = result.rows
        if (data.length !== 0) {
          this.echartDataProcessing(data, param.kssj, param.jssj, zt)
        } else {
          this.echartDataProcessing([], param.kssj, param.jssj, zt)
        }
      }).catch((err) => {
        console.log('err', err)
      })
    },
    getUntilList (dwxh) {
      const obj = {
        dwxh: dwxh
      }
      Api.getUntilList(JSON.stringify(obj)).then(res => {
        const data = res.rows
        const collegeArr = []
        data.map(item => {
          const obj = {
            label: item.DWJC,
            value: item.DWXH
          }
          collegeArr.push(obj)
        })
        this.unitArr = this.convertToTree(collegeArr)
        this.dwxh = this.unitArr[0].value
      })
    },
    getSliderChange (val) {
      const zt = (val + 1).toString()
      if (zt === '3') {
        const obj = {
          kssj: moment(this.form.kssj).format('YYYY'),
          jssj: moment(this.form.jssj).format('YYYY'),
          dwxh: this.dwxh
        }
        this.getJZBLSJWCQK(obj, zt)
      } else {
        const obj = {
          kssj: moment(this.form.kssj).format('YYYY'),
          jssj: moment(this.form.jssj).format('YYYY'),
          dwxh: this.dwxh
        }
        this.getCumCompleteData(obj, zt)
      }
    },
    getChartsOption (legendData, seriesData, xAxisData, dataArr, zt) {
      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#ccc'
            }
          },
          formatter: function (params) {
            let str = params[0].name + '<br/>'
            for (let i = 0; i < params.length; i++) {
              if (zt === '1' && dataArr.length !== 0) {
                dataArr.map(item => {
                  if ((item.ND + '年') === params[i].seriesName && (item.jd) === (params[i].dataIndex + 1).toString()) {
                    const time = minutesToHours(item.wcljnum, 2)
                    str += `${params[i].marker} ${params[i].seriesName} : ${time} / ${params[i].value}% <br />`
                  }
                })
              } else if (zt === '2' && dataArr.length !== 0) {
                dataArr.map(item => {
                  if ((item.ND + '年') === params[i].seriesName && (item.MON + '月') === params[i].name) {
                    const time = minutesToHours(item.wcljnum, 2)
                    str += `${params[i].marker} ${params[i].seriesName} : ${time} / ${params[i].value}% <br />`
                  }
                })
              } else if (zt === '3' && dataArr.length !== 0) {
                dataArr.map(item => {
                  if ((item.ND + '年') === params[i].seriesName && item.RQ.substring(5, 10) === params[i].name) {
                    str += `${params[i].marker} ${params[i].seriesName} : ${params[i].value}% <br />`
                  }
                })
              }
            }
            return str
          }
        },
        legend: {
          top: 10,
          data: legendData
        },
        color: ['#4CB909', '#0DCFC8', '#409EFF', '#E9BA18'],
        grid: {
          top: '18%',
          left: '4%',
          right: '4%',
          bottom: '20%'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          nameTextStyle: {
            color: '#D5D5D5'
          },
          axisLine: {
            lineStyle: { color: '#D5D5D5' }
          },
          splitLine: {
            show: true,
            interval: 'auto',
            lineStyle: {
              color: '#EBEBEB',
              width: 1,
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#788AA2'
          },
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          name: '时间完成率 (%)',
          min: 0,
          max: 120,
          boundaryGap: [0, '100%'],
          nameTextStyle: {
            color: '#6E7C8C'
          },
          axisLine: {
            lineStyle: { color: '#D5D5D5' }
          },
          splitLine: {
            show: true,
            interval: 'auto',
            lineStyle: {
              color: '#EBEBEB',
              width: 1,
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#788AA2'
          }
        },
        series: seriesData
      }
      this.optionsData = options
    },
    echartDataProcessing (dataArr, kssj, jssj, zt) {
      if (zt === '1') {
        const dataYear = fillYears(kssj, jssj)
        const legendData = []
        dataYear.map(item => {
          legendData.push(item + '年')
        })
        const seriesData = []
        const newData = this.getQuarterProcessing(dataArr)
        legendData.map(item => {
          const obj = {
            name: item,
            type: 'line',
            data: []
          }
          if (newData.length !== 0) {
            newData.map(element => {
              if (item.substring(0, 4) * 1 === element.ND * 1) {
                let str = 0
                if (element.zbnum === 0 || element.zbnum === null) {
                  str = 0
                } else {
                  str = (element.wcljnum === 0 || element.wcljnum === null) ? 0 : (parseFloat(element.wcljnum / element.zbnum) * 100).toFixed(2)
                }
                obj.data.push(str)
              }
            })
          }
          seriesData.push(obj)
        })
        const xAxisData = ['春季', '夏季', '秋季', '冬季']
        this.getChartsOption(legendData, seriesData, xAxisData, newData, zt)
      } else if (zt === '2') {
        const dataYear = fillYears(kssj, jssj)
        const legendData = []
        dataYear.map(item => {
          legendData.push(item + '年')
        })
        const unitArr = []
        const unitStr = this.dwxh
        dataArr.map(unitItem => {
          if (unitStr === unitItem.DWXH) {
            unitArr.push(unitItem)
          }
        })
        const seriesData = []
        legendData.map(item => {
          const obj = {
            name: item,
            type: 'line',
            data: []
          }
          if (unitArr.length !== 0) {
            unitArr.map(element => {
              if (item.substring(0, 4) * 1 === element.ND * 1) {
                let str = 0
                if (element.zbnum === 0 || element.zbnum === null) {
                  str = 0
                } else {
                  str = (element.wcljnum === 0 || element.wcljnum === null) ? 0 : (parseFloat(element.wcljnum / element.zbnum) * 100).toFixed(2)
                }
                obj.data.push(str)
              }
            })
          }
          seriesData.push(obj)
        })
        const xAxisData = []
        for (let i = 0; i < 12; i++) {
          xAxisData.push((i + 1) + '月')
        }
        this.getChartsOption(legendData, seriesData, xAxisData, unitArr, zt)
      } else {
        const dataYear = fillYears(kssj, jssj)
        const legendData = []
        dataYear.map(item => {
          legendData.push(item + '年')
        })
        const xAxisData = this.generateChartOptions()
        const seriesData = []
        const newArr = this.completeData(dataArr, zt)
        console.log('newArr', newArr)
        legendData.map(item => {
          const obj = {
            name: item,
            type: 'line',
            data: []
          }
          if (newArr.length !== 0) {
            newArr.map(element => {
              if (item.substring(0, 4) * 1 === element.ND * 1) {
                const zb = element.JZSJ + element.BLSJ
                const wc = element.JZWCSJ + element.BLWCSJ
                let rate = 0
                if (zb !== 0 && !isNaN(zb) && wc !== 0 && !isNaN(wc)) {
                  rate = ((wc / zb) * 100).toFixed(2)
                } else {
                  rate = 0
                }
                obj.data.push(rate)
              }
            })
          }
          seriesData.push(obj)
        })
        this.getChartsOption(legendData, seriesData, xAxisData, newArr, zt)
      }
    },
    // 点击单位
    getUnitData (val) {
      const zt = (this.value + 1).toString()
      if (zt === 2) {
        const obj = {
          kssj: moment(this.form.kssj).format('YYYY'),
          jssj: moment(this.form.jssj).format('YYYY'),
          dwxh: val
        }
        this.$refs.unitCascader.dropDownVisible = false
        this.getCumCompleteData(obj, zt)
      } else {
        const obj = {
          kssj: moment(this.form.kssj).format('YYYY'),
          jssj: moment(this.form.jssj).format('YYYY'),
          dwxh: val
        }
        this.$refs.unitCascader.dropDownVisible = false
        this.getJZBLSJWCQK(obj, zt)
      }
    },
    // 季度数据处理
    getQuarterProcessing (arr) {
      const quarterlyData = []
      // 按年份和季度分组计算数据
      const groupedData = arr.reduce((acc, curr) => {
        const year = curr.ND
        const quarter = Math.ceil(curr.MON / 3)
        const key = `${year}-${quarter}`
        if (!acc[key]) {
          acc[key] = {
            ND: year,
            jd: quarter.toString(),
            wcnum: 0,
            wcljnum: 0,
            zbnum: 0
          }
        }
        acc[key].wcnum += curr.wcnum
        acc[key].wcljnum += curr.wcljnum
        acc[key].zbnum += curr.zbnum

        return acc
      }, {})
      // 转换为数组形式
      for (const key in groupedData) {
        quarterlyData.push(groupedData[key])
      }
      return quarterlyData
    },
    // x轴日数据处理
    generateChartOptions () {
      // 生成 X 轴数据
      const xAxisData = []
      const startDate = new Date(new Date().getFullYear(), 0, 1)
      const endDate = new Date(new Date().getFullYear(), 11, 31)
      const currentDate = new Date(startDate)

      // eslint-disable-next-line no-unmodified-loop-condition
      while (currentDate <= endDate) {
        const month = String(currentDate.getMonth() + 1).padStart(2, '0')
        const day = String(currentDate.getDate()).padStart(2, '0')
        const date = `${month}-${day}`
        xAxisData.push(date)
        currentDate.setDate(currentDate.getDate() + 1)
      }
      return xAxisData
    },
    // 数据补全
    completeData (data, zt) {
      const completedData = []
      if (zt === '1') {
        // 补全缺失的quarter值
        for (let i = 1; i <= 4; i++) {
          const existingData = data.find(item => item.quarter === i.toString().padStart(2, '0'))
          if (existingData) {
            completedData.push(existingData)
          } else {
            const newData = {
              timestamp: '2023',
              num: 0,
              quarter: i.toString().padStart(2, '0')
            }
            completedData.push(newData)
          }
        }
      } else if (zt === '2') {
        const months = [
          '01', '02', '03', '04', '05', '06',
          '07', '08', '09', '10', '11', '12'
        ]
        for (let i = 0; i < 12; i++) {
          const month = months[i]
          const existingData = data.find(item => item.timestamp.endsWith(month))
          if (existingData) {
            completedData.push(existingData)
          } else {
            const newData = {
              timestamp: `2023-${month}`,
              num: 0,
              quarter: `2023-${month}`
            }
            completedData.push(newData)
          }
        }
      } else {
        // 获取数据中的最小和最大年份
        let minYear = Infinity
        let maxYear = -Infinity
        for (let i = 0; i < data.length; i++) {
          const year = parseInt(data[i].ND)
          if (year < minYear) {
            minYear = year
          }
          if (year > maxYear) {
            maxYear = year
          }
        }
        // 补全缺失的数据
        for (let year = minYear; year <= maxYear; year++) {
          for (let month = 1; month <= 12; month++) {
            for (let day = 1; day <= 31; day++) {
              const date = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
              const existingData = data.find(item => item.RQ === date)
              if (!existingData) {
                data.push({
                  ND: String(year),
                  JZSJ: 0,
                  BLSJ: 0,
                  JZWCSJ: 0,
                  BLWCSJ: 0,
                  RQ: date
                })
              }
            }
          }
        }
        // 按日期排序数据
        data.sort((a, b) => new Date(a.RQ) - new Date(b.RQ))
      }
      return data
    },
    getFormatTooltip (val) {
      if (val === 0) {
        return '季'
      } else if (val === 1) {
        return '月'
      } else if (val === 2) {
        return '日'
      }
    },
    // 表格
    getTableData () {
      const param = {
        dwxh: this.currentUser.sysUnit.unitId,
        kssj: moment(this.form.kssj).format('YYYY'),
        jssj: moment(this.form.jssj).format('YYYY')
      }
      Apis.getHistoriesAllFlightTimeForTable(JSON.stringify(param)).then(res => {
        const data = res.rows
        // // 去重方法
        const newDatas = getArrayObjectDeduplication(data, 'DWXH')
        const handleArrs = []
        newDatas.map(item => {
          const rowObj = this.filterTableRow(data, item, param)
          handleArrs.push(...rowObj)
        })
        this.colSpan.rowArray = getColumnFun(handleArrs, 'DWXH')
        this.tableData = handleArrs
        // 折线图赋值
        this.echartDataProcessing(data, param.kssj, param.jssj, '2')
      })
    },
    filterTableRow (data, unitData, timeObj) {
      const row = data.filter(item => {
        return item.DWXH === unitData.DWXH
      })
      let unitNdArr = ''
      const unitArr = []
      for (let i = (timeObj.jssj * 1); i >= timeObj.kssj; i--) {
        unitNdArr = row.filter(items => {
          return items.ND * 1 === i
        })
        const tableObj = {
          DWXH: row[0].DWXH,
          zbnum: '-',
          wcnum: '-',
          ND: i,
          DWJC: row[0].DWJC,
          '1_Time': '0',
          '1_WCL': '-',
          WCLStr_1: '0',
          '2_Time': '0',
          '2_WCL': '-',
          WCLStr_2: '0',
          '3_Time': '0',
          '3_WCL': '-',
          WCLStr_3: '0',
          '4_Time': '0',
          '4_WCL': '-',
          WCLStr_4: '0',
          '5_Time': '0',
          '5_WCL': '-',
          WCLStr_5: '0',
          '6_Time': '0',
          '6_WCL': '-',
          WCLStr_6: '0',
          '7_Time': '0',
          '7_WCL': '-',
          WCLStr_7: '0',
          '8_Time': '0',
          '8_WCL': '-',
          WCLStr_8: '0',
          '9_Time': '0',
          '9_WCL': '-',
          WCLStr_9: '0',
          '10_Time': '0',
          '10_WCL': '-',
          WCLStr_10: '0',
          '11_Time': '0',
          '11_WCL': '-',
          WCLStr_11: '0',
          '12_Time': '0',
          '12_WCL': '-',
          WCLStr_12: '0'
        }
        const rowObj = unitNdArr.reduce(function (prev, cur, index) {
          const num = Math.floor(cur.zbnum / 60)
          prev.zbnum = num
          const unitTime = `${cur.MON}_Time`
          const unitWcl = `${cur.MON}_WCL`
          const unitWclStr = `WCLStr_${cur.MON}`
          const unitWclNum = `${cur.MON}_WCLJ`
          let str = ''
          let str2 = ''
          if (cur.zbnum === 0 || cur.zbnum === null) {
            str = '100%'
            str2 = 100
          } else {
            str2 = (cur.wcljnum === 0 || cur.wcljnum === null) ? '0%' : (parseFloat(cur.wcljnum / cur.zbnum) * 100).toFixed(2)
            str = (cur.wcljnum === 0 || cur.wcljnum === null) ? '0%' : (parseFloat(cur.wcljnum / cur.zbnum) * 100).toFixed(2) + '%'
          }
          prev[unitTime] = minutesToHours(cur.wcnum, 2)
          prev[unitWclNum] = minutesToHours(cur.wcljnum, 2)
          prev[unitWcl] = str
          prev[unitWclStr] = str2
          return prev
        }, tableObj)
        unitArr.push(rowObj)
      }
      return unitArr
    },
    convertToTree (list) {
      const tree = []
      const map = {}
      list.forEach(item => {
        const parentValue = item.value.slice(0, -2)
        if (map[parentValue]) {
          if (!map[parentValue].children) {
            map[parentValue].children = []
          }
          map[parentValue].children.push(item)
        } else {
          tree.push(item)
        }
        map[item.value] = item
      })
      return tree
    }
  }
}
</script>
<style lang="less" scoped>
.top {
  height: 25vh;
  background: #fff;
  margin-bottom: 18px;
  position: relative;
  .block {
    width: 30%;
    position: absolute;
    top: 8px;
    right: 30px;
    display: flex;
    align-items: center;
    justify-content: right;
    /deep/.el-slider__runway {
      margin: 10px 0;
    }
  }
}
</style>
